<template>
  <ToolbarButton
    type="dropdown"
    icon="i-mdi-watermark"
    title="水印"
    dropdown-icon="i-ri-arrow-down-s-fill"
    popover-width="320px"
    popover-placement="bottom-start"
    :large-icon="props.largeIcon"
    :hide-text="props.hideText"
    @main-click="toggleWatermark"
  >
    <template #dropdown>
      <div class="page-watermark-dropdown">
        <!-- 第一行：字体、大小、加粗 -->
        <div class="watermark-style-section">
          <div class="watermark-style-row">
            <!-- 字体 -->
            <div class="watermark-style-item">
              <select v-model="tempFontFamily" class="watermark-select">
                <option
                  v-for="font in fontOptions"
                  :key="font.value || 'default'"
                  :value="font.value || ''"
                >
                  {{ getFontLabel(font) }}
                </option>
              </select>
            </div>
            <!-- 大小 -->
            <div class="watermark-style-item">
              <select v-model="tempFontSize" class="watermark-select">
                <option
                  v-for="size in fontSizeOptions"
                  :key="size.value"
                  :value="size.value"
                >
                  {{ getSizeLabel(size) }}
                </option>
              </select>
            </div>
            <!-- 加粗 -->
            <div class="watermark-style-item watermark-bold-item">
              <button
                type="button"
                class="watermark-bold-btn"
                :class="{ active: tempFontBold }"
                @click="tempFontBold = !tempFontBold"
                title="加粗"
              >
                <i class="i-mdi-format-bold watermark-bold-icon"></i>
              </button>
            </div>
          </div>
        </div>

        <!-- 第二行：文本输入 -->
        <div class="watermark-text-input">
          <input
            v-model="tempWatermarkText"
            type="text"
            class="watermark-input"
            placeholder="请输入水印文本"
          />
        </div>

        <!-- 第三行：类型选择 -->
        <div class="watermark-type-section">
          <div class="watermark-type-options">
            <div
              v-for="type in watermarkTypes"
              :key="type.value"
              class="watermark-type-option"
              :class="{ active: tempWatermarkType === type.value }"
              @click="tempWatermarkType = type.value"
            >
              <!-- 预览区域 -->
              <div
                class="watermark-preview"
                :class="`watermark-preview-${type.value}`"
                :style="{
                  backgroundImage: `url(${getPreviewImage(type.value)})`,
                }"
              ></div>
              <!-- 类型标签 -->
              <div class="watermark-type-label">{{ type.label }}</div>
            </div>
          </div>
        </div>

        <!-- 确定和取消按钮 -->
        <div class="watermark-actions">
          <button
            class="watermark-btn watermark-btn-cancel"
            @click="handleCancel"
          >
            取消
          </button>
          <button
            class="watermark-btn watermark-btn-confirm"
            @click="handleConfirm"
          >
            确定
          </button>
        </div>
      </div>
    </template>
  </ToolbarButton>
</template>

<script setup lang="ts">
import { inject, ref, type Ref } from "vue";
import type { PageOption } from "../../../../types";
import ToolbarButton from "../../../button/index.vue";
import { closeAllToolbarPopups } from "../../../button/src/utils/toolbarPopupManager";
import { defaultDicts } from "../../../../config/constants";

defineOptions({
  name: "PageWatermark",
});

const props = withDefaults(
  defineProps<{
    largeIcon?: boolean;
    hideText?: boolean;
  }>(),
  {
    largeIcon: false,
    hideText: true,
  }
);

// 注入页面配置
const pageOptions = inject<Ref<PageOption>>("page");

// 水印类型选项
const watermarkTypes = [
  { label: "紧凑型", value: "compact" },
  { label: "宽松型", value: "loose" },
];

// 字体选项
const fontOptions = defaultDicts.fonts;

// 字体大小选项（只保留常用的大小）
const fontSizeOptions = defaultDicts.fontSizes.filter(
  (size) =>
    typeof size.value === "string" &&
    (size.value.includes("px") || size.value.includes("pt"))
) as Array<{
  label?: string | { en_US?: string; zh_CN?: string };
  value: string;
}>;

// 临时状态（用于编辑，不直接修改 pageOptions）
const tempWatermarkText = ref("");
const tempWatermarkType = ref("compact");
const tempFontFamily = ref("SimSun");
const tempFontSize = ref("30px");
const tempFontBold = ref(false);

// 初始化数据
const initData = () => {
  const watermark = pageOptions?.value?.watermark;
  if (watermark) {
    tempWatermarkText.value = watermark.text || "";
    tempWatermarkType.value = watermark.type || "compact";
    tempFontFamily.value = watermark.fontFamily || "SimSun";
    // 将 fontSize 转换为字符串，匹配 fontSizeOptions 中的格式
    const savedFontSize = watermark.fontSize || 30;
    // 查找匹配的 fontSize 选项，如果没有则使用 "30px"
    const matchingSize = fontSizeOptions.find((s) => {
      if (s.value.includes("px")) {
        const size = parseInt(s.value.replace("px", ""));
        return size === savedFontSize;
      }
      return false;
    });
    tempFontSize.value = matchingSize
      ? matchingSize.value
      : `${savedFontSize}px`;
    tempFontBold.value = watermark.fontWeight === "bold";
  } else {
    tempWatermarkText.value = "";
    tempWatermarkType.value = "compact";
    tempFontFamily.value = "SimSun";
    tempFontSize.value = "30px";
    tempFontBold.value = false;
  }
};

// 初始化
initData();

// 获取字体标签
const getFontLabel = (font: {
  label?: string | { en_US?: string; zh_CN?: string };
  value: string | null;
}) => {
  if (typeof font.label === "string") return font.label;
  if (font.label?.zh_CN) return font.label.zh_CN;
  if (font.label?.en_US) return font.label.en_US;
  return font.value || "默认字体";
};

// 获取大小标签
const getSizeLabel = (size: {
  label?: string | { en_US?: string; zh_CN?: string };
  value: string;
}) => {
  if (typeof size.label === "string") return size.label;
  if (size.label?.zh_CN) return size.label.zh_CN;
  if (size.label?.en_US) return size.label.en_US;
  return size.value;
};

// 处理取消
const handleCancel = () => {
  initData(); // 恢复初始状态
  closeAllToolbarPopups(undefined, undefined, ["select", "popover"]);
};

// 处理确定
const handleConfirm = () => {
  if (!pageOptions?.value) return;

  // 解析字体大小（可能包含 px 或 pt）
  let fontSize = 30;
  const sizeValue = tempFontSize.value;
  if (sizeValue.includes("px")) {
    fontSize = parseInt(sizeValue.replace("px", ""));
  } else if (sizeValue.includes("pt")) {
    // 将 pt 转换为 px（1pt ≈ 1.33px）
    fontSize = Math.round(parseFloat(sizeValue.replace("pt", "")) * 1.33);
  } else {
    fontSize = parseInt(sizeValue) || 30;
  }

  // 应用设置到 pageOptions
  pageOptions.value.watermark = {
    type: tempWatermarkType.value,
    text: tempWatermarkText.value || "",
    alpha: 0.2,
    fontColor: "#000000",
    fontSize: fontSize,
    fontFamily: tempFontFamily.value || "SimSun",
    fontWeight: tempFontBold.value ? "bold" : "normal",
  };

  closeAllToolbarPopups(undefined, undefined, ["select", "popover"]);
};

// 切换水印下拉菜单
const toggleWatermark = () => {
  initData();
};

// 获取预览图片（用户需要自己放置图片）
const getPreviewImage = (type: string) => {
  // 返回预览图片路径，用户需要自己放置图片
  // 紧凑型：compact-watermark.png
  // 宽松型：loose-watermark.png
  return type === "compact"
    ? ""
    : "";
};
</script>

<style scoped lang="scss">
.page-watermark-dropdown {
  padding: 20px;
  min-width: 320px;
  background-color: var(--editor-bg-color, #ffffff);
}

.watermark-text-input {
  margin-bottom: 16px;
}

.watermark-label {
  display: block;
  font-size: 12px;
  color: var(--editor-text-color-secondary, #666);
  margin-bottom: 8px;
  font-weight: 500;
}

.watermark-input {
  width: 100%;
  padding: 10px 14px;
  border: 1.5px solid var(--editor-border-color, #d9d9d9);
  border-radius: 6px;
  font-size: 14px;
  outline: none;
  box-sizing: border-box;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  background-color: var(--editor-bg-color, #ffffff);
  color: var(--editor-text-color, #333);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);

  &:hover {
    border-color: var(--editor-border-color-hover, #bfbfbf);
  }

  &:focus {
    border-color: var(--editor-primary-color, #1890ff);
    box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
  }

  &::placeholder {
    color: var(--editor-text-color-placeholder, #bfbfbf);
  }
}

.watermark-type-section {
  margin-bottom: 16px;
}

.watermark-type-options {
  display: flex;
  gap: 12px;
}

.watermark-type-option {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  background-color: transparent;

  &:hover {
    .watermark-preview {
      border-color: var(--editor-primary-color, #1890ff);
    }
  }

  &.active {
    .watermark-preview {
      border-color: var(--editor-primary-color, #1890ff);
      border-width: 2px;
    }
  }
}

.watermark-type-check {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: var(--editor-primary-color, #1890ff);
  font-size: 14px;
  background-color: var(--editor-primary-color, #1890ff);
  border-radius: 50%;
  color: #ffffff;
}

.watermark-preview {
  width: 100%;
  aspect-ratio: 210 / 297; /* A4比例 */
  max-width: 80px;
  margin-bottom: 8px;
  position: relative;
  overflow: hidden;
  border-radius: 6px;
  background-color: var(--editor-bg-color, #ffffff);
  border: 1px solid var(--editor-border-color-light, #f0f0f0);
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.04);
  transition: border-color 0.25s cubic-bezier(0.4, 0, 0.2, 1),
    border-width 0.25s cubic-bezier(0.4, 0, 0.2, 1);

  // 添加渐变遮罩让背景更柔和
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      135deg,
      rgba(255, 255, 255, 0.2) 0%,
      rgba(255, 255, 255, 0.05) 50%,
      rgba(255, 255, 255, 0.2) 100%
    );
    pointer-events: none;
    border-radius: 6px;
    z-index: 1;
  }
}

.watermark-type-label {
  font-size: 13px;
  color: var(--editor-text-color, #333);
  font-weight: 600;
  margin-top: 4px;
  letter-spacing: 0.3px;
}

.watermark-style-section {
  margin-bottom: 16px;
}

.watermark-style-row {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.watermark-style-item {
  display: flex;
  flex-direction: column;
  flex: 1;
}

.watermark-bold-item {
  flex: 0 0 auto;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  min-width: 36px;
  height: 36px;
}

.watermark-style-label {
  font-size: 11px;
  color: var(--editor-text-color-secondary, #666);
  font-weight: 500;
}

.watermark-select {
  width: 100%;
  padding: 8px 12px;
  padding-right: 32px;
  border: 1.5px solid var(--editor-border-color, #d9d9d9);
  border-radius: 6px;
  font-size: 13px;
  outline: none;
  box-sizing: border-box;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  background-color: var(--editor-bg-color, #ffffff);
  color: var(--editor-text-color, #333);
  cursor: pointer;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.02);

  &:hover {
    border-color: var(--editor-border-color-hover, #bfbfbf);
  }

  &:focus {
    border-color: var(--editor-primary-color, #1890ff);
    box-shadow: 0 0 0 3px rgba(24, 144, 255, 0.1);
  }

  // 美化下拉选项
  option {
    padding: 8px 12px;
    background-color: var(--editor-bg-color, #ffffff);
    color: var(--editor-text-color, #333);
  }
}

.watermark-select-small {
  padding: 6px 8px;
  font-size: 12px;
}

.watermark-bold-btn {
  width: 100%;
  height: 100%;
  min-width: 36px;
  min-height: 36px;
  padding: 0;
  margin: 0;
  border: none;
  outline: none;
  background: none;
  background-color: var(--editor-bg-color, #ffffff);
  border-radius: 6px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease;

  &:hover {
    background-color: var(--editor-border-color, #d9d9d9);
  }

  &.active {
    background-color: var(--editor-border-color, #d9d9d9);

    &:hover {
      background-color: var(--editor-border-color, #d9d9d9);
    }
  }

  &:active {
    opacity: 0.8;
  }
}

.watermark-bold-icon {
  font-size: 20px;
  width: 20px;
  height: 20px;
  color: var(--editor-text-color, #333);
  display: inline-block;
}

.watermark-actions {
  display: flex;
  gap: 10px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid var(--editor-border-color-light, #f0f0f0);
}

.watermark-btn {
  flex: 1;
  padding: 10px 16px;
  border: 1.5px solid transparent;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  outline: none;
  font-weight: 600;
  letter-spacing: 0.3px;

  &:active {
    transform: scale(0.98);
  }
}

.watermark-btn-cancel {
  background-color: var(--editor-bg-color, #ffffff);
  color: var(--editor-text-color, #333);
  border-color: var(--editor-border-color, #d9d9d9);

  &:hover {
    background-color: var(--editor-bg-color-hover, #fafafa);
    border-color: var(--editor-border-color-hover, #bfbfbf);
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  }

  &:active {
    background-color: var(--editor-bg-color-active, #f0f0f0);
  }
}

.watermark-btn-confirm {
  background: linear-gradient(
    135deg,
    var(--editor-primary-color, #1890ff) 0%,
    #1677ff 100%
  );
  color: #ffffff;
  border-color: var(--editor-primary-color, #1890ff);
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.2);

  &:hover {
    background: linear-gradient(135deg, #40a9ff 0%, #1890ff 100%);
    border-color: #40a9ff;
    box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
    transform: translateY(-1px);
  }

  &:active {
    background: linear-gradient(135deg, #1677ff 0%, #0958d9 100%);
    box-shadow: 0 1px 2px rgba(24, 144, 255, 0.2);
  }
}

// 美化滚动条样式（针对webkit内核浏览器：Chrome、Edge、Safari等）
.page-watermark-dropdown {
  // 美化select下拉菜单的滚动条
  select {
    // 注意：原生select的下拉菜单滚动条样式控制有限
    // 这里主要针对可以自定义的部分
  }

  // 美化所有可滚动元素的滚动条
  * {
    &::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }

    &::-webkit-scrollbar-track {
      background: var(--editor-bg-color-light, #f5f5f5);
      border-radius: 4px;
    }

    &::-webkit-scrollbar-thumb {
      background: #d9d9d9;
      border-radius: 4px;
      border: 2px solid var(--editor-bg-color-light, #f5f5f5);
      transition: background 0.2s ease;

      &:hover {
        background: #bfbfbf;
      }

      &:active {
        background: #8c8c8c;
      }
    }

    &::-webkit-scrollbar-corner {
      background: var(--editor-bg-color-light, #f5f5f5);
    }
  }
}
</style>
